<template>
  <view class="styleContainer" :style="{ backgroundImage: 'url(' + srcBg + ')' }">

    <view class="aititle-task"> 剩余面试次数：{{ rightCount }}</view>

    <!-- 页面标签菜单 -->
    <TabsSwiper :tabList="tabList" ref="tabsSwiper" :current="current" bgColor="transparent" tabsWidth="412"
      marginLeft="10" :scale="barScale" @tabsChange="tabsChange" />

    <swiper class="swiper-box" :duration="200" :current="swiperCurrent" @transition="handleTransition"
      @animationfinish="handleAnimation">

      <swiper-item class="swiper-item ">
        <!-- 搜索 -->
        <view class="styleSearchContainer" @click="clickSearch" v-if="!isInputMode">
          <u-input class="styleInput" placeholder="搜索职业的名称" :focus="isFocus" v-model="inputText" :clearable="false"
            :placeholder-style="placeholderStyle" @click="clickInput" disabled />
          <image class="styleSearchIcon" :src="srcInputSearchIcon"></image>
        </view>
        <view class="styleSearchInputModeContainer" v-else>
          <u-input class="styleInput" placeholder="搜索职业的名称" :focus="inputModeIsFocus" v-model="inputModeText"
            :clearable="false" :placeholder-style="placeholderStyle" @input="onInputChanged" @blur="onBlur" />
          <view class="styleClearContainer">
            <image class="styleClearIcon" :src="srcInputSearchClose" @click="clickClear" v-if="isShowClear"></image>
            <view class="styleCancelText" @click="clickCancel">取消</view>
          </view>
        </view>
        <view class="styleMajorList" v-if="isShowMajorList" :style="{ height: contentHeight }" @click="clickScrollView">
          <scroll-view class="styleScrollView" scroll-y="true" @scrolltoupper="onRefresh" @scrolltolower="onLoadMore"
            @scroll="onScroll" :upper-threshold="50" :lower-threshold="50">
            <view class="styleItem" v-for="(item, index) in list" :key="index" @click="clickMajorItem(item)">
              <rich-text class="styleName" :nodes="highLightText(item.positionName)"></rich-text>
              <view class="styleLine" v-if="index != list.length - 1"></view>
            </view>
            <view class="styleBottom" v-if="isShowBottom"></view>
          </scroll-view>
        </view>
        <view class="styleEmpty" @click="clickEmptyPage" v-if="isShowEmpty" :style="{ height: contentHeight }">没有找到符合的内容
        </view>

        <!-- 职业分类 -->
        <MajorFilterView v-show="isShowMajorFilter" :cateType="majorListParam.cateType" :rectTop="searchBottom"
          :specialStyle="{ height: contentHeight }" @closeBubble="closeBubble" ref="filterListRef"
          @clickItem="clickMajorItem" />
      </swiper-item>

      <!-- 面试结果 -->
      <swiper-item class="swiper-item">
        <view id="swiper-item-1">
          <InterviewRelustAI :updateCount="updateRelustCount" />
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>
<script>
import { matchPositionListNew } from "@/api/modules/career";
import { getpositionTagAndParentList } from "@/api/modules/major";
import MajorFilterView from "./MajorFilterView.vue";
import InterviewRelustAI from "./InterviewRelustAI.vue";

import ShareMixin from "@/mixins/share";
import TabsSwiper from "./TabsSwiper.vue";
import {
  reqZhituGetCareer,
  reqZhituHasFinished,
} from "@/api/modules/company.js";
export default {
  mixins: [ShareMixin],
  components: {
    MajorFilterView,
    TabsSwiper,
    InterviewRelustAI,
  },
  props: {
    rightCount: {
      type: Number,
      default: 3,
    },
    pageIndex: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    pageIndex(newValue, oldValue) {
      if (newValue) {
        this.$refs.tabsSwiper.$refs.tabs.setFinishCurrent(newValue);
        this.swiperCurrent = newValue;
        this.current = newValue;
        this.$bus.$emit("updateContentInterviewListAI", true);
      }
    },
  },

  data() {
    return {
      shareTitle: "查查你的专业的就业前景",
      pagesLength: 0,
      isFocus: false,
      inputModeIsFocus: true,
      inputText: "",
      inputModeText: "",
      degreeText: "本科",
      isInputMode: false,
      isShowClear: false,
      isShowMajorList: false,
      isShowEmpty: false,
      isShowBubble: false,
      isShowMajorFilter: true,
      srcGoBack:
        this.$imgBaseSelf + "career/positionDictionary/major_go_back.webp",
      srcGoHome: this.$imgBaseSelf + "home-b.png",
      srcInputSearchIcon:
        this.$imgBaseSelf + "career/positionDictionary/input_search_icon.webp",
      srcMajorTriangle:
        this.$imgBaseSelf + "career/positionDictionary/major_triangle.webp",
      srcInputSearchClose:
        this.$imgBaseSelf + "career/positionDictionary/input_seach_close.webp",
      placeholderStyle:
        "color: rgba(0,0,0,0.25);font-weight:400;font-size:28rpx;",
      list: [],
      positionTree: [],
      loadingType: "nomore", //"normal",
      majorListParam: {
        cateType: "30",
        pageNo: 1,
        pageSize: 10,
        pages: 0,
      },
      statusBarHeight: 0,
      bubbleMarginTop: 0,
      contentHeight: 0,
      isHome: true,
      srcBg:
        this.$imgBaseSelf +
        "career/positionDictionary/bg_major_searchhome.webp",
      isShowBottom: false,
      sharePath: "/pagesSub/careerNew/positionDictionary/MajorSearch",
      isShowAnim: false,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      userNum: 0,

      selectedPageIndex: 0,

      tabList: [
        {
          name: "选择职业面评",
        },
        {
          name: "我的结果",
        },
      ],
      current: 0,
      swiperCurrent: 0,
      barScale: 1,
      swiperHeight: 400,
      screenWidth: 412,
      searchBottom: 0,
      updateRelustCount: 0,
    };
  },
  created() {
    this.pagesLength = getCurrentPages().length;
  },
  onLoad(opt) {
    uni.setNavigationBarColor({
      frontColor: "#000000",
      backgroundColor: "",
    });
    this.zhituGetStartInfo();
  },
  mounted() {
    this.getStatusBarHeight();
  },
  onReady() {
    // this.current = this.rightCount == this.userNum ? 1 : 0;
    // this.swiperCurrent = this.current;
    this.getSearchBottom();
  },

  methods: {
    getSearchBottom() {
      const { screenHeight } = uni.getSystemInfoSync();
      uni
        .createSelectorQuery()
        .in(this)
        .select(".styleSearchContainer")
        .boundingClientRect((rect) => {
          this.searchBottom = rect.bottom;
        })
        .exec();
    },

    tabsChange(index) {
      if (index == 1) {
        this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
        if (!this.personId) {
          this.current = this.swiperCurrent;
          this.$emit("shouldlogin");
          return;
        }
      }
      this.swiperCurrent = index;
    },
    handleTransition(e) {
      let dx = e.detail.dx;
      this.$refs.tabsSwiper.$refs.tabs.setDx(dx);
      // dx = Math.abs(dx);
      // let range = 1;
      // let change = 0;
      // let moveX = 0;
      // let width = 412;
      // if (dx < width / 2) {
      //   moveX = dx;
      // } else if (dx < (width * 2) / 3) {
      //   return;
      // } else {
      //   moveX = width - dx;
      // }
      // change = ((moveX / width) * range).toFixed(2);
      // this.barScale = 1 - change;
    },
    handleAnimation(e) {
      let current = e.detail.current;
      // console.log("切换tab-----------",current);
      this.$refs.tabsSwiper.$refs.tabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
      if (current == 1) {
        this.updateRelustCount += 1;
      }
      // this.changeSwiper();
    },
    closeBubble() {
      this.isShowBubble = false;
    },
    getStatusBarHeight() {
      const res = uni.getSystemInfoSync();
      this.statusBarHeight = res.statusBarHeight;
      console.log("statusBarHeight:" + this.statusBarHeight + "px");
      this.bubbleMarginTop = this.statusBarHeight + uni.upx2px(88) + "px";
      console.log("bubbleMarginTop:" + this.bubbleMarginTop);
      const screenHeight = res.windowHeight;
      console.log("windowHeight:" + screenHeight);
      this.contentHeight =
        screenHeight - uni.upx2px(196) - this.statusBarHeight + "px";
      console.log("contentHeight:" + this.contentHeight);

      const platform = res.platform;
      console.log("手机平台" + platform);
    },
    clickBack() {
      console.log("clickBack");
      uni.navigateBack();
    },
    clickHome() {
      uni.switchTab({
        url: "/pages/index/index",
      });
    },
    clickSearch() {
      console.log("clickSearch");
      this.isInputMode = true;
      this.isShowMajorFilter = false;
      this.srcBg =
        this.$imgBaseSelf + "career/positionDictionary/bg_major_search.webp";
    },
    clickInput() {
      console.log("clickInput");
      this.isInputMode = true;
      this.isShowMajorList = true;
      this.isShowBubble = false;
      this.isShowMajorFilter = false;
      this.srcBg =
        this.$imgBaseSelf + "career/positionDictionary/bg_major_search.webp";
    },
    clickClear() {
      this.inputModeText = "";
      this.isShowClear = false;
      this.isShowEmpty = false;
      this.loadingType = "nomore"; //"normal";
      this.majorListParam.pageNo = 1;
      this.list = [];
      this.isShowMajorFilter = false;
      this.srcBg =
        this.$imgBaseSelf + "career/positionDictionary/bg_major_search.webp";

      this.inputModeIsFocus = false;
      setTimeout(() => {
        this.inputModeIsFocus = true;
      }, 0);
    },
    clickCancel() {
      console.log("clickCancel");
      this.isShowMajorList = false;
      this.isInputMode = false;
      this.inputModeText = "";
      this.isShowEmpty = false;
      this.isShowClear = false;
      this.list = [];
      this.isShowMajorFilter = true;
      this.srcBg =
        this.$imgBaseSelf +
        "career/positionDictionary/bg_major_searchhome.webp";
    },
    onInputChanged(value) {
      console.log("---value1:" + value);
      this.loadingType = "normal";
      this.majorListParam.pageNo = 1;
      if (value && value.length > 0) {
        this.isShowClear = true;
        this.zhituSearchOn(value);
      } else {
        this.isShowClear = false;
        this.isShowEmpty = false;
        this.list = [];
      }
    },
    // 搜索
    zhituSearchOn(key) {
      const params = { matchName: key, pageNo: 1, pageSize: 99 };
      matchPositionListNew(params)
        .then((res) => {
          console.log("🚀 ~ .搜索 ~ res:", res);
          if (res.code == 200) {
            this.list = res.data;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },

    // 获取职业列表(数据写死固定的)
    zhituGetStartInfo() {
      if (this.isLoading) {
        return;
      }
      if (!this.personId) {
        return;
      }
      this.isLoading = true;
      let params = {
        personId: this.personId,
      };
      reqZhituGetCareer(params)
        .then((res) => {
          this.isLoading = false;
          if (res.code == 200) {
            this.positionTree = res.data.positionTree;
            if (this.inputModeText) {
              this.list = this.zhituHandleSearchOn(this.inputModeText);
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "error",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },

    zhituHandleSearchOn(key) {
      const searchStuffArray = [];
      this.positionTree.forEach((secondDimension) => {
        secondDimension.children.forEach((thirdDimension) => {
          thirdDimension.children.forEach((item) => {
            if (item.positionName.includes(key)) {
              searchStuffArray.push(item);
            }
          });
        });
      });
      return searchStuffArray;
    },

    onRefresh() {
      console.log("onRefresh");
    },
    onLoadMore() {
      console.log("onLoadMore");
      this.loadMore();
    },
    onScroll(event) {
      // console.log(event);
    },
    getData() {
      const params = {
        pageNo: this.majorListParam.pageNo,
        pageSize: this.majorListParam.pageSize,
        tagLevel: 3,
        tagType: 10,
        cateType: this.majorListParam.cateType,
        matchName: this.inputModeText,
      };
      console.log("请求参数:", params);
      getpositionTagAndParentList(params)
        .then((res) => {
          console.log("列表数据:", res);
          if (res.code == 200) {
            this.list = res.data;
            this.majorListParam.pageNo++;
            this.majorListParam.pages = res.pageparam.pages;
            if (this.majorListParam.pageNo > res.pageparam.pages) {
              this.loadingType = "nomore";
            }
            if (res.data.length == 0) {
              this.isShowMajorList = false;
              this.isShowEmpty = true;
            } else {
              this.isShowMajorList = true;
              this.isShowEmpty = false;
            }
            if (this.inputModeText == "") {
              this.isShowClear = false;
              this.isShowEmpty = false;
              this.list = [];
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          console.log("finally");
        });
      this.isShowBottom = false;
    },
    loadMore() {
      console.log("loadMore");
      if (this.loadingType == "normal") {
        this.loadingType = "loading";
        setTimeout((res) => {
          // this.list = this.list.concat(this.list);
          const params = {
            pageNo: this.majorListParam.pageNo,
            pageSize: this.majorListParam.pageSize,
            tagLevel: 3,
            tagType: 10,
            cateType: this.majorListParam.cateType,
            matchName: this.inputModeText,
          };
          console.log("加载更多请求参数:", params);
          getpositionTagAndParentList(params)
            .then((res) => {
              console.log("加载更多列表数据:", res);
              if (res.code == 200) {
                this.list.push(...res.data);
                this.majorListParam.pageNo++;
                if (this.majorListParam.pageNo > res.pageparam.pages) {
                  this.loadingType = "nomore";
                  console.log("总条数:" + this.list.length);
                  this.isShowBottom = true;
                }
                if (this.inputModeText == "") {
                  this.isShowEmpty = false;
                }
              } else {
                uni.showToast({
                  title: res.status_desc,
                  icon: "none",
                });
              }
            })
            .catch((e) => {
              console.log(e);
            })
            .finally(() => {
              console.log("finally");
            });
          this.loadingType = "normal";
        }, 0);
      }
    },
    highLightText(content) {
      if (!content) {
        return;
      }
      const regex = new RegExp(this.inputModeText, "gi");
      const highlightedText = content.replace(
        regex,
        '<span style="color:#F75A3E;">' + this.inputModeText + "</span>"
      );
      return highlightedText;
    },
    clickTitleDegree() {
      console.log("clickTitleDegree");
      if (this.isShowBubble) {
        this.isShowBubble = false;
      } else {
        this.isShowBubble = true;
      }
      this.isShowMajorList = false;
      this.isInputMode = false;
      this.inputModeText = "";
      this.isShowEmpty = false;
      this.isShowClear = false;
      this.list = [];
      this.isShowMajorFilter = true;
      this.srcBg =
        this.$imgBaseSelf +
        "career/positionDictionary/bg_major_searchhome.webp";
    },
    clickUndergraduate() {
      console.log("clickUndergraduate");
      this.isShowBubble = false;
      if (this.degreeText == "本科") return;
      this.majorListParam.cateType = "30";
      this.degreeText = "本科";
      this.$refs.filterListRef.currentIndexZero();
    },
    clickJuniorCollege() {
      console.log("clickJuniorCollege");
      this.isShowBubble = false;
      if (this.degreeText == "专科") return;
      this.majorListParam.cateType = "10";
      this.degreeText = "专科";
      this.$refs.filterListRef.currentIndexZero();
    },
    clickEmptyPage() {
      console.log("clickEmptyPage");
      this.isInputMode = false;
      this.inputModeText = "";
      this.isShowEmpty = false;
      this.isShowClear = false;
      this.clickCancel();
    },

    clickMajorItem(item) {
      this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
      if (!this.personId) {
        this.$emit("shouldlogin");
        return;
      }

      if (this.rightCount == 0) {
        uni.showToast({
          title: "您当前剩余面试次数为0，无法参与面试",
          icon: "none",
        });
        return;
      }
      var pid = "";
      if (this.isShowMajorList) {
        pid = item.ylPositionId; // 搜索的用ylPositionId
      } else {
        // 推荐的用positionId，三级职业的用valueId
        pid = item.positionId ? item.positionId : item.valueId;
      }
      this.positionId = pid;
      this.checkStartOnAIInterView(pid);
    },

    // 校验是否完成本场职业AI面评
    checkStartOnAIInterView(positionId) {
      this.isLoading = true;
      let params = {
        personId: this.personId,
        positionId: positionId,
        modelType: "zph",
      };
      reqZhituHasFinished(params)
        .then((res) => {
          this.isLoading = false;
          if (res.code == 200) {
            let infoId = res.data.infoId;
            if (res.data.status == "not_finished") {
              let record = res.data.id;
              this.record = record;
              this.$emit(
                "onGoToInterview",
                "zph",
                positionId,
                this.record,
                "",
                infoId
              );
            } else {
              uni.navigateTo({
                url:
                  "/pagesSub/companyCenter/interviewAI/room/interviewReady?from=zph&careerId=" +
                  positionId,
              });
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },
    onBlur() {
      console.log("onBlur");
    },
    clickScrollView() {
      console.log("clickScrollView");
      if (this.list.length <= 0) {
        this.clickCancel();
      }
    },
    startAnimation() {
      this.isShowAnim = true;
      setTimeout(() => {
        console.log("setTimeout");
        this.isShowAnim = false;
      }, 500);
    },
  },
};
</script>
<style lang="scss" scoped>
@keyframes animationScale {
  from {
    transform: scale(0);
    //从左上角开始缩放
    transform-origin: left top;
  }

  to {
    transform: scale(1);
  }
}

.styleContainer {
  background-size: 100% 100%;
  height: calc(100vh - 362rpx);

  .swiper-box {
    height: calc(100vh - 323rpx);
    background: linear-gradient(180deg, #ffffff 0%, #f4f6f8 100%);
    border-radius: 32rpx 32rpx 0rpx 0rpx;
    padding-top: 20rpx;
  }

  .styleSearchContainer {
    display: flex;
    position: relative;
    height: 80rpx;
    background-color: #f4f6f8;
    margin-left: 32rpx;
    margin-right: 32rpx;
    // box-shadow: 0rpx 0rpx 18rpx 0rpx rgba(114, 165, 195, 0.3);
    border-radius: 16rpx;
    // filter: blur(0px);
    margin-top: 15rpx;
    margin-bottom: 4rpx;

    .styleInput {
      height: 80rpx;
      margin-left: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100vw; // width: 100%;
      margin-right: 80rpx;
    }

    .styleSearchIcon {
      position: absolute;
      top: 50%;
      right: 28rpx;
      transform: translateY(-50%);
      width: 40rpx;
      height: 40rpx;
    }

    .overlay {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  }
  .styleSearchInputModeContainer {
    display: flex;
    position: relative;
    height: 80rpx;
    background-color: #ffffff;
    margin-left: 32rpx;
    margin-right: 32rpx;
    box-shadow: 0rpx 0rpx 18rpx 0rpx rgba(114, 165, 195, 0.3);
    border-radius: 16rpx;
    filter: blur(0px);
    margin-top: 15rpx;
    margin-bottom: 4rpx;

    .styleInput {
      height: 80rpx;
      margin-left: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100vw; // width: 100%;
      margin-right: 140rpx;
    }

    .styleClearContainer {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: 50%;
      right: 28rpx;
      transform: translateY(-50%);

      .styleClearIcon {
        width: 32rpx;
        height: 32rpx;
      }

      .styleCancelText {
        font-weight: 400;
        color: #888888;
        line-height: 36rpx;
        font-size: 28rpx;
        margin-left: 12rpx;
      }
    }
  }
}

.styleMajorList {
  background-color: transparent;
  margin-top: 12rpx;

  .styleScrollView {
    height: calc(100vh - 110rpx);

    .styleItem {
      display: flex;
      flex-direction: column;
      width: 100vw;
      justify-content: center;

      .styleName {
        font-weight: 400;
        color: #222222;
        line-height: 40rpx;
        font-size: 30rpx;
        margin-top: 36rpx;
        margin-left: 32rpx;
        margin-right: 32rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }

      .styleDesciption {
        font-weight: 400;
        color: #888888;
        line-height: 40rpx;
        margin-top: 16rpx;
        margin-left: 32rpx;
        margin-right: 32rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }

      .styleLine {
        margin-left: 32rpx;
        margin-right: 32rpx;
        height: 2rpx;
        background: #dde7f9;
        margin-top: 36rpx;
      }
    }

    .styleBottom {
      background-color: transparent;
      height: 50rpx;
    }
  }
}
.aititle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  &-text {
    margin-left: 32rpx;
    margin-top: 16rpx;
    font-size: 44rpx;
    font-weight: 800;
    color: #000000;
    line-height: 60rpx;
  }
  &-task {
    margin-right: 32rpx;
    font-size: 26rpx;
    font-weight: 400;
    color: #666666;
    // line-height: 36rpx;
    position: absolute;
    right: 0rpx;
    top: 28rpx;
  }
  &-on {
    margin-left: 16rpx;
    font-size: 48rpx;
    font-weight: 800;
    color: #333333;
  }
}

.styleTopContainer {
  .aititle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    &-text {
      margin-left: 32rpx;
      margin-top: 16rpx;
      font-size: 44rpx;
      font-weight: 800;
      color: #000000;
      line-height: 60rpx;
    }
    &-task {
      margin-right: 32rpx;
      font-size: 26rpx;
      font-weight: 400;
      color: #666666;
      line-height: 36rpx;
    }
    &-on {
      margin-left: 16rpx;
      font-size: 48rpx;
      font-weight: 800;
      color: #333333;
    }
  }

  .styleEmpty {
    width: 100vw;
    height: calc(100vh - 266rpx);
    font-weight: 400;
    color: #222222;
    line-height: 36rpx;
    font-size: 28rpx;
    text-align: center;
    padding-top: 48rpx;
  }

  .topTriangleBubbleContainer {
    position: fixed;
    top: 0;
    left: 50%;
    z-index: 99;

    .topTriangleBubble {
      margin-top: -6rpx;
      width: 100rpx;
      height: 120rpx;
      background: #ffffff;
      border-radius: 10rpx;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.16);

      .styleBubbleText {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 28rpx;
        font-weight: bold;
        justify-content: center;
      }
    }

    .topTriangleBubble:before {
      content: "";
      width: 0px;
      height: 0px;
      border-bottom: 8px solid #ffffff;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      position: absolute;
      top: -8rpx;
      left: 4rpx;
    }
  }
}
.styleHasAnimation {
  animation: animationScale 0.5s ease-in-out alternate;
}
</style>